package ynu.edu.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import org.springframework.web.bind.annotation.*;
import ynu.edu.dao.IStudentDao;
import ynu.edu.po.Student;

import java.util.List;

@CrossOrigin(origins = "http://localhost:5174", allowedHeaders = "*", allowCredentials = "true")
@RestController
@RequestMapping(value = "/stu")
@Tag(name = "学生信息相关服务")
public class StudentController {
    @Resource
    private IStudentDao sDao;

    @Operation(summary = "Hello测试方法")
    @GetMapping(value = "/hello")
    public String hello() {
        return "Student Controller";
    }

    @Operation(summary = "获取所有学生信息")
    @GetMapping(value = "/all")
    public List<Student> getAllStudents() {
        return (List<Student>) sDao.findAll();
    }

    @Operation(summary = "新增学生信息")
    @Transactional
    @PostMapping(value = "/createStu")
    public Student createStu(@RequestBody Student stu) {
        // 不需要检查主键，直接保存用户信息
        return sDao.save(stu);
    }

    @Transactional
    @Operation(summary = "注销账号")
    @DeleteMapping(value = "/deleteStu")
    public void deleteStu(@RequestParam(value = "id") Long id) {
        sDao.deleteById(id);
    }

    @Transactional
    @Operation(summary = "更新学生信息")
    @PutMapping(value = "/updateStu")
    public void updateStu(@RequestBody Student stu) {
        sDao.save(stu);
    }

    @Operation(summary = "登录服务")
    @Parameters({
            @Parameter(name = "id", description = "学号"),
            @Parameter(name = "pwd", description = "密码")
    })
    @PostMapping(value = "/login")
    public Student login(@RequestParam(value = "id") String stuId, @RequestParam(value = "pwd") String password) {
        return sDao.findStudentByStuIdAndPassword(Long.valueOf(stuId), password);
    }
}
